package file

import (
	"fmt"
	"time"

	"code.google.com/p/gomonitor/tsdb"
)

func filePrefix(m tsdb.Metric) string {
	return m.Scope + "." + m.Var + "."
}

func fileName(root string, m tsdb.Metric, t time.Time) string {
	return root + "/" + filePrefix(m) + fmt.Sprintf("%d", t.UnixNano())
}

func dotFields(r rune) bool {
	return r != '.'
}

type sortableFiles []struct {
	t    int64
	path string
}

func (l sortableFiles) Len() int {
	return len(l)
}

func (l sortableFiles) Less(i, j int) bool {
	return l[i].t < l[j].t
}

func (l sortableFiles) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func dataToDatapoint(d Data, i, sz int) tsdb.Datapoint {
	f := d.Value
	dp := tsdb.Datapoint{
		Value: make([]*float64, sz),
		Ts:    time.Unix(0, d.Ts),
	}
	dp.Value[i] = &f
	return dp
}

func timeRangeIntersects(start, end, tStart, tEnd time.Time) bool {
	return (start.After(tStart) || start.Equal(tStart)) && (start.Before(tEnd) || start.Equal(tEnd)) ||
		(end.Equal(tStart) || end.After(tStart)) && (end.Before(tEnd) || end.Equal(tEnd)) ||
		start.Before(tStart) && end.After(tEnd)
}
